#    Copyright (C) 2019 Mason Hock <mason@masonhock.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
#

import os
import yaml

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

from .misc import seconds_to_timestamp
from .settings import CONFIG_DIR


class Library(dict):
    def save(self):
        with open(CONFIG_DIR + "/library.yaml", "w") as f:
            yaml.dump(dict(self), f)

    def load(self):
        if os.path.isfile(CONFIG_DIR + "/library.yaml"):
            with open(CONFIG_DIR + "/library.yaml", "r") as f:
                self.update(yaml.safe_load(f))

    def add_track(self, track):
        self.update({track["track_id"]: track})

    def add_jamendo_track(self, data):
        track = {
            "track_id": "jamendo:" + data["id"],
            "track_name": data["name"],
            "track_duration": data["duration"],
            "track_position": data["position"],
            "artist_id": "jamendo:" + data["artist_id"],
            "artist_name": data["artist_name"],
            "album_id": "jamendo:" + data["album_id"],
            "album_name": data["album_name"],
            "album_date": data["releasedate"],
            "album_image": data["album_image"],
        }
        self.add_track(track)

    def get_track(self, track_id):
        if track_id in self:
            return self[track_id]

    def remove_track(self, track_id):
        return self.pop(track_id, False)

    def populate_liststore(self, liststore):
        for track_id, track_data in self.items():
            icon = None
            track = track_data["track_position"]
            title = track_data["track_name"]
            artist = track_data["artist_name"]
            album = track_data["album_name"]
            length = seconds_to_timestamp([track_data["track_duration"]])[0]
            date = track_data["album_date"]

            liststore.append(
                [track_id, icon, track, title, artist, album, length, date]
            )

            liststore.set_sort_column_id(2, Gtk.SortType.ASCENDING)
            liststore.set_sort_column_id(7, Gtk.SortType.ASCENDING)
            liststore.set_sort_column_id(4, Gtk.SortType.ASCENDING)
